package com.strive.village.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.strive.village.common.Result;
import com.strive.village.entity.SysMenu;
import com.strive.village.entity.SysRoleMenu;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 菜单管理类
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController {
    /**
     * 根据ID获取一条菜单信息
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result menuInfo(@PathVariable(name = "id") Long id) {
        return Result.success(sysMenuService.getById(id));
    }

    /**
     * 获取菜单列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result menuList() {
        List<SysMenu> menus = sysMenuService.tree();
        return Result.success(menus);
    }

    /**
     * 新增保存
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result saveMenu(@RequestBody SysMenu sysMenu) {
        sysMenu.setCreated(LocalDateTime.now());
        sysMenuService.save(sysMenu);
        return Result.success("保存成功");
    }

    /**
     * 更新菜单信息
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result updateMenu(@RequestBody SysMenu sysMenu){
        sysMenu.setUpdated(LocalDateTime.now());
        sysMenuService.updateById(sysMenu);

        // 清除与该菜单相关的用户缓存
        sysUserService.clearUserAuthorityInfoByMenuId(sysMenu.getId());
        return Result.success("更新成功");
    }

    /**
     * 删除菜单
     */
    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    @Transactional // 保证事务的原子性
    public Result deleteMenu(@PathVariable(name = "id") Long menuId){
        // 判断是否为父级菜单
        int count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", menuId));
        if (count > 0){
            return Result.fail("请先删除子菜单");
        }

        sysMenuService.removeById(menuId);
        sysUserService.clearUserAuthorityInfoByMenuId(menuId);
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("menu_id", menuId));
        return Result.success("删除成功");
    }
}
